package com.vf.admin.client.controller;

import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppMingxiChongzhiDao;
import com.vf.admin.client.dao.AppOrderDao;
import com.vf.admin.client.dao.AppSetupDao;
import com.vf.admin.client.service.*;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.fiwork.util.IOSVerify;
import com.vf.admin.miaodong.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.vf.admin.common.Constants.dingdan_status_dfk;
import static com.vf.admin.common.Constants.dingdan_zhiFuLeiXing_zfb;
import static com.vf.admin.utils.RandomUtil.getOrderIdByUUId;

@RestController
@RequestMapping("/app/recharge")
public class AppRechargeController extends ClientBaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AppUserService appUserService;
    @Autowired
    private AppSetupDao appSetupDao;
    @Autowired
    private AppOrderDao appOrderDao;
    @Autowired
    AppMingxiChongzhiDao appMingxiChongzhiDao;
    @Autowired
    private AppOrderService appOrderService;
    @Autowired
    private AppMingXiZuanShiService appMingXiZuanShiService;
    @Autowired
    private AppMingxiChongzhiService appMingxiChongzhiService;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    private AgentUserService agentUserService;
    @Autowired
    private AppInvitationRecordService appInvitationRecordService;
    @Autowired
    private AppSetupService appSetupService;
    @Autowired
    AppPrivilegeService appPrivilegeService;
    @Autowired
    AppCzMoneyService appCzMoneyService;

    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    public Result diamondRechargeAlipay(HttpServletRequest request, Double money, Integer id) {
        try {
            AppSetup setup = appSetupService.get();
            if(setup.getOpenRecharge() == 0) {
                return this.errorJSON(setup.getRechargeTip());
            }
            Map<String, Object> data = new HashMap<>();
            if (money == null || money <= 0) {
                return this.errorJSON("请你输入充值金额!");
            }
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);
            AppCzMoney appCzMoney = appCzMoneyService.get(id);
            BigDecimal getDiamond = appCzMoney.getDiamonds().add(appCzMoney.getGive());
            //添加订单记录
            String orderNum = getOrderIdByUUId();
            AppOrder appOrder = new AppOrder();
            appOrder.setCreatetime(new Date());
            appOrder.setOrdernum(orderNum);
            appOrder.setCzMoneyId(id);
            appOrder.setMoney(new BigDecimal(appCzMoney.getMoney()));
            appOrder.setStatus(Constants.dingdan_status_dfk);
            appOrder.setType(3);
            appOrder.setUserid(user.getId());
            appOrder.setPic(user.getPic());
            appOrder.setNick(user.getNick());
            appOrder.setPhone(user.getLoginname());
            appOrder.setNum(getDiamond);
            appOrderDao.save(appOrder);
            data.put("orderNum", orderNum);
            return this.sucessJSON(data);
        } catch (Exception e) {
            logger.error("支付宝充值异常:", e);
            return this.errorJSON("服务器繁忙，请您稍后重试!");
        }
    }

    /**
     * ios内购回调
     *
     * @param receipt
     * @return
     */
    @RequestMapping("/iosPaySuccess")
    public Result iosPaySuccess(@RequestParam("orderNo") String orderNo, @RequestParam("receipt") String receipt) {
        try {
            receipt = URLDecoder.decode(receipt, "utf-8");
            logger.info("----------------------receipt Str:" + receipt);
            Map<String, Object> result = IOSVerify.buyAppVerify(receipt);
            if (result.get("success").toString().equals("true")) {
                String out_trade_no = (String) result.get("transaction_id");
                //根据订单号、支付状态、支付方式获取预订单
                AppOrder topup = appOrderService.getByOrdernum(orderNo, 3, dingdan_status_dfk);
                //判断预订单是否存在
                if (!StringUtils.isEmpty(topup)) {
                    AppUser user = appUserService.get(topup.getUserid());
                    //存在则更改预订单支付状态
                    appOrderService.updateStastusYzf(out_trade_no, 1);
                    //判断首冲
                    BigDecimal getDiamond = topup.getNum();
                    //添加用户钻石金额
                    appUserService.updateZuanShi(user.getId(), getDiamond);
                    //增加用户累积充值金额
                    appUserService.updateLeijiChongzhi(user.getId(), topup.getMoney());
                    //添加钻石明细
                    appMingXiZuanShiService.addMingxi(user.getId(), getDiamond, 1, "钻石充值");
                    //添加充值明细
                    appMingxiChongzhiService.addMingxi(user.getId(), getDiamond, 1, topup.getMoney(), out_trade_no,topup.getMobileSpec());
                    //完成充值任务
                    appDailyTasController.getAwardOnce(topup.getUserid(), ClientConstants.TaskOnce.RECHARGE_FIRST);
                    //如果有上级发放用户充值提成
                    addAward(topup);
                    //升级贵族
                    appPrivilegeService.isUpLevel(user);
                    logger.info("IOS内购回调成功，充值入账成功");
                }
            } else {
                return errorJSON("IOS内购验证失败");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 邀请用户充值增加父级提成
     *
     * @param order
     */
    public void addAward(AppOrder order) {
        AppInvitationRecord record = appInvitationRecordService.getShangji(order.getUserid());
        if (record != null) {
            AppSetup appSetup = appSetupService.get();
            BigDecimal divide = order.getNum().multiply(appSetup.getRechargeInvite()).setScale(2, BigDecimal.ROUND_HALF_UP);
            appUserService.addDiamonds(record.getPuserid(), divide, "邀请用户充值提成");
        }
    }
}
